package com.xiangwei.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 读取src目录下属性配置文件的工具类
 * 
 * @author yancy
 */
public final class ReadPropertiesUtil {
	// 对属性文件的流进行缓存
	private static Map<String, InputStream> propertiesMap = new HashMap<String, InputStream>();
	private static ReadPropertiesUtil readProperties = null;

	private ReadPropertiesUtil() {
	}

	/**
	 * 根据指定属性文件获取该属性文件中属性名为key的属性值 author: yancy time: 2014下午11:04:49
	 * 
	 * @param propertiesFileName
	 *            属性文件名，包括后缀
	 * @param key
	 *            要获取的属性的key值
	 * @return 获取失败的话返回null
	 */
	public static String getPropertiesValue(String propertiesFileName,
			String key) {
		if (readProperties == null) {
			readProperties = new ReadPropertiesUtil();
		}
		String value = null;
		Properties properties = new Properties();
		try {
			InputStream localInputStream = null;
			if (propertiesMap.containsKey(propertiesFileName)) {
				localInputStream = propertiesMap.get(propertiesFileName);
			} else {
				localInputStream = readProperties.getClass().getClassLoader()
						.getResourceAsStream(propertiesFileName);
			}
			properties.load(localInputStream);
			value = properties.getProperty(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/**
	 * 获取配置文件config.properties 所有键值
	 * author: ylx
	 * 
	 * */
	public static String getPropertiesMap(String propertiesFileName,Integer score){
		if (readProperties == null) {
			readProperties = new ReadPropertiesUtil();
		}
		String map = null;
		Properties properties = new Properties();
		try {
			InputStream localInputStream = null;
			if (propertiesMap.containsKey(propertiesFileName)) {
				localInputStream = propertiesMap.get(propertiesFileName);
			} else {
				localInputStream = readProperties.getClass().getClassLoader()
						.getResourceAsStream(propertiesFileName);
			}
			properties.load(localInputStream);
			for (Object key : properties.keySet()) {
				if (key.toString().indexOf("score")>=0) {
					String[] split = key.toString().split("-");
					try {
						if (Integer.parseInt(split[0].replace("score", ""))<=score && Integer.parseInt(split[0+1])>=score) {
							map = properties.get(key).toString();
						}
					} catch (Exception e) {
						if (Integer.parseInt(split[0].replace("score", ""))==score) {
							map = properties.get(key).toString();
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 获取属性文件config.properties获取该属性文件中属性名为key的属性值 
	 * author: yancy 
	 * time:2014下午11:04:49
	 * @param key
	 *            要获取的属性的key值
	 * @return 获取失败的话返回null
	 */
	public static String getPropertiesValue(String key) {
		if (readProperties == null) {
			readProperties = new ReadPropertiesUtil();
		}
		String value = null;
		Properties properties = new Properties();
		try {
			InputStream localInputStream = null;
			if (propertiesMap.containsKey("config.properties")) {
				localInputStream = propertiesMap.get("config.properties");
			} else {
				localInputStream = readProperties.getClass().getClassLoader()
						.getResourceAsStream("config.properties");
			}
			properties.load(localInputStream);
			value = properties.getProperty(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/**
	 * 获取配置里面的属性并生成列表
	 * @param filePath
	 * @param property
	 * @return
	 */
	public static List<Object> getProperty(String filePath, String property){
		ReadPropertiesUtil propertiesUtil = new ReadPropertiesUtil();
		InputStream inputStream = propertiesUtil.getClass().getClassLoader().getResourceAsStream(filePath);
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
		} catch (IOException ioE) {
			ioE.printStackTrace();
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String Str = properties.getProperty(property);
		String[] Strs = Str.split(",");
		List<Object> list = new ArrayList<Object>();
		for (int i = 0; i < Strs.length; i++) {
			list.add(Strs[i]);
		}
		return list;
	}
	
	 /** 
	     * 修改或添加键值对 如果key存在，修改, 反之，添加。 
	     * @param filePath 文件路径，即文件所在包的路径，例如：java/util/config.properties 
	     * @param key 键 
	     * @param value 键对应的值 
	     */  
	    public static void writeData(String filePath, String key, String value) {  
	        //获取绝对路径  
	        filePath = ReadPropertiesUtil.class.getResource("/" + filePath).toString();  
	        //截掉路径的”file:/“前缀  
//	        filePath = filePath.substring(6);  //windows 环境下
	        filePath = filePath.substring(5);  //linux环境下
	        System.out.println("****fliePath ***:"+filePath);
	        Properties prop = new Properties();  
	        try {  
	            File file = new File(filePath);  
	            if (!file.exists())  
	                file.createNewFile();  
	            InputStream fis = new FileInputStream(file);  
	            prop.load(fis);  
	            //一定要在修改值之前关闭fis  
	            fis.close();  
	            OutputStream fos = new FileOutputStream(filePath);  
	            prop.setProperty(key, value);  
	            //保存，并加入注释  
	            prop.store(fos, "Update '" + key + "' value");  
	            fos.close();  
	        } catch (IOException e) {  
	            System.err.println("Visit " + filePath + " for updating " + value + " value error");  
	        }  
	    } 
	    
}
